package com.u.finance.call.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.u.finance.call.entity.RepaymentSchedule;
import com.u.finance.call.mapper.RepaymentScheduleMapper;
import com.u.finance.call.service.IRepaymentScheduleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-03-31
 */
@Service
public class RepaymentScheduleServiceImpl extends ServiceImpl<RepaymentScheduleMapper, RepaymentSchedule> implements IRepaymentScheduleService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Scheduled(cron = "0 0 17 * * ?") // 每天17点执行
    public Boolean createNotifySchedule() {

        List<RepaymentSchedule> willPayment = this.list(new QueryWrapper<RepaymentSchedule>()
                .eq("DATE_SUB(payment_date, INTERVAL 3 DAY)", LocalDate.now()));


        for (RepaymentSchedule repaymentSchedule : willPayment) {
            notify(1, repaymentSchedule.getUserId(), "您的还款日即将到来，请及时还款");
        }

        List<RepaymentSchedule> overDatePayment = this.list(new QueryWrapper<RepaymentSchedule>()
                .lt("payment_date", LocalDate.now())
                .eq("status", "未还款"));

        for (RepaymentSchedule repaymentSchedule : overDatePayment) {
            // 未还款的，进行催收
            rocketMQTemplate.convertAndSend("notify", repaymentSchedule);
        }

        return true;
    }

    private Boolean notify(Integer type, Long toUserId, String content) {
        switch (type) {
            case 1:
                // 短信通知
                break;
            case 2:
                // 邮件通知
                break;
            case 3:
                // 站内信通知
                break;
            default:
                break;
        }
        return true;
    }
}
